package br.com.tiaspider.services.im;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import br.com.tiaspider.services.listener.GtalkPacketListener;

public class GtalkService implements IMService{
	
	private static final String email = "tia.webspider@gmail.com";
	private static final String pass = "76247587";
	private static final ConnectionConfiguration config = new ConnectionConfiguration( "talk.google.com" , 5222 , "gmail.com" );
	private XMPPConnection connection ;
	
	public GtalkService() {
		
		connection = new XMPPConnection( config );
		
	}

	public void start() throws Exception {
		
		try{
			connection.connect();
			
			//
			//efetua o login
			//
			connection.login( email , pass ); 
			
			connection.addPacketListener( new GtalkPacketListener( this ) , new MessageTypeFilter( Message.Type.chat ) ); //Listener dos pacotes recebidos
			
			Presence presence = new Presence( Presence.Type.available );
			connection.sendPacket( presence );
			
		}catch( XMPPException ex ){
			
			throw new Exception( ex );
			
		}
		
		System.out.println( "Conectado." );
	}

	public XMPPConnection getConnection() {
		return connection;
	}

	public void sendMessage(String message, String destination) {
		
		Message msg = new Message();
		msg.setTo( destination );
		msg.setBody( message );
		System.out.println( "Sending reply..." );
		
		connection.sendPacket( msg ); 

	}

	public void stop() {
		connection.disconnect( new Presence( Presence.Type.unavailable ) );
	}

	public boolean isConnected() {
		return connection.isConnected();
	}

	public void executeCommand(String cmd, String replyTo) {
		
		this.sendMessage( "not supported yet" , replyTo  );
		
	}
		
}
